import React from 'react';
import Upload from 'rc-upload';
import { loc, GateWay, obj_str, Btn, WaitUmd, useCmd } from 'sui';

const Base =({ hcmd, hcheck, label, action, path, className, disabled=false, color="blue" }) => {
    const umd = useCmd();

    const props = {
        name: path,
        action: action,
        multiple: false,
        beforeUpload(file) {
            if (hcheck) {
                const e = hcheck(file);
                if (e) {
                    alert(e);
                    return false;
                }
            }

            umd.startWait();
            return true;
        },
        onSuccess(ret) {
            umd.endWait();

            if (hcmd) {
                hcmd(ret);
            }
        },
        onError(err, ret) {
            umd.setErr(`${loc("l_568")}: ${obj_str(ret, "message")}`);
        }
    };

    return (
        <div className={className}>
            <Upload {...props}>
                <Btn color={color} disabled={disabled}>{label}</Btn>
            </Upload>
            <WaitUmd umd={umd}/>
        </div>
    );
};

const Kup =(props) => {
    const hcheck = (file) => {
        const fn = file.name;

        if ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" !== file.type && ".xlsx" !== fn.slice(-5)) {
            return loc("l_626");
        }

        return null;
    };

    const action = GateWay.url_xlsx();

    return <Base {...props} hcheck={hcheck} action={action}/>;
};

const KEsop =(props) => {
    const hcheck = (file) => {
        const fn = file.name;
        if (fn !== "tech.zip") {
            return `${loc("l_594")}: tech.zip`;
        }

        return null;
    };

    const action = GateWay.url_esop();

    return <Base {...props} hcheck={hcheck} action={action}/>;
};

const KImg =(props) => {
    const isSize = (size) => size / 1024 / 1024 / 1024 <= 2;

    const isPng = (type) => type === 'image/png';

    const hcheck = (file) => {
        const fn = file.name;
        const ckname = props.ckname;

        if (ckname !== fn) {
            return `${loc("l_570")} ${ckname}`;
        }

        if (!isPng(file.type)) {
            return loc("l_571");
        }

        if (!isSize(file.size)) {
            return loc("l_572");
        }

        return null;
    };

    const action = GateWay.url_upload();

    return <Base {...props} hcheck={hcheck} action={action}/>;
};

export {KImg, KEsop, Kup};
